import { exec } from 'child_process';
import crypto from 'crypto';
import https from 'https';
import { findVideoNameFromStdout, findVideoSizeFromStdout, getVideoSource } from './utils';
import { Response } from '../node_modules/@types/express';
import { ReadStream } from 'fs';
import { ServerResponse, IncomingMessage } from 'http';

// download 720p by video_link on http
export async function download720HTTPByVideoLink(video_link: string, res: Response) {
    let videoSource = await getVideoSource(video_link);
    download720HTTPByVideoSource(videoSource+'', res);
}


// download 720p by video_source on http
export function download720HTTPByVideoSource(video_source: string, res: Response) {
    https.get(video_source, (videoStream: IncomingMessage) => {
        let vh = videoStream.headers;
        let v_cl = vh["content-length"] || 0;
        let v_ct = vh["content-type"] || "";
        res.set({
            "Content-Length": v_cl,
            "Content-Type": v_ct,
            "Content-Disposition": `attachment; filename="geekshine.${v_ct.substring(6)}"`
        });
        videoStream.pipe(res);
    })
}


// download 720P to ftp server
export function download720FTP(video_link: string) {
    let hashName = crypto.createHmac('sha256', video_link).update('i love nodejs').digest('hex')
    return new Promise((resolve, reject) => {
        exec(`cd /var/ftp && rm -rf ${hashName}.mp4 && youtube-dl --no-playlist -f best -o '${hashName}.%(ext)s' ${video_link}`, (error, stdout, stderr) => {
            if (error) reject(error);
            if (stderr) reject(stderr);
            resolve({
                videoName: findVideoNameFromStdout(stdout),
                videoSize: findVideoSizeFromStdout(stdout),
                info: stdout
            });
        })
    })
}


// download 1080p to ftp server
export function download1080FTP(bestVideoN: number, audioN: number, video_link: string) {
    let hashName = crypto.createHmac('sha256', video_link).update('i love javascript').digest('hex')
    return new Promise((resolve, reject) => {
        exec(`cd /var/ftp && youtube-dl --no-playlist -f ${bestVideoN}+${audioN} -o '${hashName}.%(ext)s' ${video_link}`, (error, stdout, stderr) => {
            if (error) reject(error);
            if (stderr) reject(stderr);
            resolve({
                videoName: findVideoNameFromStdout(stdout),
                videoSize: findVideoSizeFromStdout(stdout),
                info: stdout
            });
        })
    })
}


// download the playlist of that video to ftp server
export function downloadList720FTP(video_link: string) {
    return new Promise((resolve, reject) => {
        exec(`cd /var/ftp && youtube-dl --yes-playlist -f best -o '%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s' ${video_link}`, (error, stdout, stderr) => {
            if (error) reject(error);
            if (stderr) reject(stderr);
            resolve(stdout);
        })
    })
}
